package com.libs.modbus;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lny on 2018/4/24.
 */

public class ScannerManager {

    public static String none = "none";


    private static final String TAG = "ScannerManager";

    private AndroidSerialportApi api;





    private static ScannerManager instance;

    public static ScannerManager getInstance() {
        if (instance == null) {
            synchronized (ScannerManager.class) {
                if (instance == null) {
                    instance = new ScannerManager();
                }
            }
        }
        return instance;
    }

    public ScannerManager() {
    }

    public void init() {
        api = new AndroidSerialportApi("/dev/ttyS2",9600);
        int open = api.open();
        api.setReadTimeOut(5000);
    }

    public void release(){
        if (api!= null && api.isOpened()){
            api.close();
        }
        api = null;
    }

    public void resetScan() {

    }

    public String scan(){
        return scan(5*1000);
    }

    public String scan(long timeout) {
        api.setReadTimeOut(timeout);
        try{
            byte[] bytes = {0x16,0x54,0x0D};
            api.write(bytes);
            byte[] read = api.read();
            if (read.length==0){
                return none;
            }else{
        String result =  new String(read);
        return replaceBlank(result);
    }
}catch (Exception e){
        e.printStackTrace();
        }
        return none;
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }




}
